package com.zlm.app;

import com.zlm.bean.AdClickEvent;
import com.zlm.bean.AdCountViewByProvince;
import com.zlm.bean.ChannelPromotionCount;
import com.zlm.bean.UserBehavior;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.net.URL;

/**
 * Author: Harbour
 * Date: 2021-05-17 11:21
 * Desc: 分析广告行为APP
 */
public class AdAnalysisApp {
    public static void main(String[] args) throws Exception {
        // step 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // step 2 获取数据源
        URL resource = AdAnalysisApp.class.getResource("/AdClickLog.csv");
        DataStream<String> inputDataStream = env.readTextFile(resource.getPath());

        // step 3 转换数据类型
        DataStream<AdClickEvent> adClickEventDataStream = inputDataStream
                .map(new MapFunction<String, AdClickEvent>() {

                    @Override
                    public AdClickEvent map(String value) throws Exception {
                        String[] fields = value.split(",");

                        // Long userId, Long adId, String province, String city, Long timestamp
                        return new AdClickEvent(
                                new Long(fields[0]),
                                new Long(fields[1]),
                                fields[2],
                                fields[3],
                                new Long(fields[4])
                        );
                    }

                })
                .assignTimestampsAndWatermarks(new AscendingTimestampExtractor<AdClickEvent>() {
                    @Override
                    public long extractAscendingTimestamp(AdClickEvent element) {
                        return element.getTimestamp() * 1000L;
                    }
                });

        // step 4 开窗统计
        adClickEventDataStream
                .keyBy(AdClickEvent::getProvince)
                .timeWindow(Time.hours(1), Time.seconds(5))
                .aggregate(new MyAggFunction(), new MyFullWindowFunction())
                .keyBy(AdCountViewByProvince::getWindowEnd)
                .process(new MyKeyedProcessFunction())
                .print();

        env.execute();
    }

    private static class MyFullWindowFunction implements WindowFunction<Long, AdCountViewByProvince, String, TimeWindow> {

        @Override
        public void apply(String s, TimeWindow window, Iterable<Long> input, Collector<AdCountViewByProvince> out) throws Exception {
            out.collect(
                    new AdCountViewByProvince(s, String.valueOf(window.getEnd()), input.iterator().next())
            );
        }
    }

    private static class MyAggFunction implements AggregateFunction<AdClickEvent, Long, Long> {

        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(AdClickEvent value, Long accumulator) {
            return accumulator + 1;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return a + b;
        }
    }

    private static class MyKeyedProcessFunction extends KeyedProcessFunction<String, AdCountViewByProvince, String> {

        @Override
        public void processElement(AdCountViewByProvince value, Context ctx, Collector<String> out) throws Exception {

            out.collect(">>>>" + ctx.getCurrentKey() + ">>>" + value);
        }
    }
}
